package org.example.pcbcircuitboard.config;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.example.pcbcircuitboard.controller.MqttSSEController;
import org.example.pcbcircuitboard.service.ReceptionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Objects;

@Component
public class MqttCallBack implements MqttCallback {
    @Autowired
    private ReceptionService receptionService;
    /**
     * 连接丢失 时触发
     * @param cause the reason behind the loss of connection.
     */
    @Override
    public void connectionLost(Throwable cause) {
        System.out.println("错误：Connection lost: " + cause.getMessage()+cause.getCause());
    }

    /**
     * 接收 到消息时触发
     * @param topic name of the topic on the message was published to
     * @param message the actual message.
     * @throws Exception if the message processing fails.
     */

    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        if (Objects.equals(topic, "pcb/report")){
            byte[] payload = message.getPayload();
            String messageString = new String(payload);
            ObjectMapper objectMapper=new ObjectMapper();
            JsonNode root=objectMapper.readTree(messageString);
//        TODO 将数据给到Service处理、封装
         boolean isSuccess=receptionService.processData(root);
         if (isSuccess){
             System.out.println("实时数据已经成功通过SSE协议推送给前端");
         }else {
             System.out.println("实时数据处理失败、SSE推送失败");
         }
        }else {
            System.out.println("接收到消息：topic=" + topic + ", message=" + message.toString());
        }

    }

    /**
     * 消息发送完成 时触发
     * @param token the delivery token associated with the message.
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        System.out.println("成功-Message delivered");
    }
    /**
     * Base64图片解析
     * @param base64Image base64编码的图片
     */
    private void saveBase64Image(String base64Image) {
        try {
            byte[] imageBytes = Base64.getDecoder().decode(base64Image);

            // 指定保存路径
            File imageFile = new File("/outImg/received_image.jpg");

            // 检查并创建目标目录
            File parentDir = imageFile.getParentFile();
            if (parentDir != null && !parentDir.exists()) {
                parentDir.mkdirs(); // 创建目录
            }

            // 保存文件
            try (FileOutputStream fos = new FileOutputStream(imageFile)) {
                fos.write(imageBytes);
            }

            System.out.println("Image saved successfully: " + imageFile.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
